package com.aiyige.page.my.order.refund;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.model.OrderEntity;
import com.aiyige.model.OrderRefundModel;
import com.aiyige.model.request.RefundDetailRequest;
import com.aiyige.page.my.order.adapter.refund.RefundImageEntity;
import com.aiyige.page.my.order.adapter.refund.RefundPicListAdapter;
import com.aiyige.page.my.order.model.RefundReasonModel;
import com.aiyige.page.photo.model.Photo;
import com.aiyige.page.photo.model.PhotoDetail;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.TimeUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.widget.CommonTitleDetailDialog;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 退款详情
 */
@Route(path = ARouterConfig.RefundApplyDetailPage, extras = ARouterConfig.EXTRA_NEED_LOGIN)
public class RefundDetailPage extends RefundBaseActivity {
    public static final int MAX_REFUND_IMAGE_NUM = 9;
    private final static int REQUEST_CODE_SELECT_IMAGE = 120;
    public static final int MAX_REFUND_REASON_INPUT_NUM = 200;

    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;

    @BindView(R.id.tv_upload_title)
    TextView tvUploadTitle;

    @BindView(R.id.tv_pay_money)
    TextView tvPayMoney; // 付款金额

    @BindView(R.id.tv_service_charge)
    TextView tvServiceCharge; // 手续费

    @BindView(R.id.tv_but_the_refund_amount)
    TextView tvButTheRefundAmount; // 可退金额

    @BindView(R.id.tv_refund_type)
    TextView tvRefundType;//退款理由

    @BindView(R.id.tv_refund_detail)
    TextView tvRefundDetail;//退款详情说明

    @BindView(R.id.ll_after_list)
    LinearLayout llAfterList;//退款进度

    @BindView(R.id.tv_refund_reason)
    TextView tvRefundReason; //买家承担手续费


    @Autowired
    String refundId;

    @Autowired
    boolean isBuyer;


    OrderEntity orderEntity = null;

    @BindView(R.id.include_images)
    View includeImages;

    OrderRefundModel orderRefundModel;

    RefundPicListAdapter refundPicListAdapter;
    RefundReasonModel selectedRefundReasonModel = new RefundReasonModel();

    @Override
    protected int getLayoutResourceId() {
        return R.layout.refund_detail_page;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        ARouter.getInstance().inject(this);
        super.onCreate(savedInstanceState);
        init();
        request();
    }

    @Override
    protected OrderEntity getOrderEntity() {
        return orderEntity;
    }

    private void init() {
        initTitleLayout(getString(R.string.view_refund_apply), true);
        tvUploadTitle.setText(getString(R.string.pic_documents));
//        etContent.setEnabled(false);
        refundPicListAdapter = new RefundPicListAdapter();
        refundPicListAdapter.setDetail(true);
        recyclerview.setLayoutManager(new GridLayoutManager(this, 4));
        refundPicListAdapter.bindToRecyclerView(recyclerview);
        refundPicListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startPhotoPage(position);
            }
        });


    }


    private void request() {
        if (TextUtils.isEmpty(refundId)) {
            ToastX.show(getString(R.string.page_does_not_exist));
            finish();
            return;
        }
        RefundDetailRequest.newBuilder().orderId(refundId).isBuyer(isBuyer).build().enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    if (!response.isSuccessful()) {
                        throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                    }
                    String json = RetrofitUtil.getResponseBodyAsString(response);
                    orderRefundModel = JsonUtil.toObject(json, OrderRefundModel.class);
                    fillViews();
                } catch (Exception e) {
                    onFailure(call, e);
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

    private void fillViews() {
        if (orderRefundModel == null) {
            return;
        }

        if (orderRefundModel.getOrderBackup() != null) {
            tvPayMoney.setText("￥" + StringUtils.priceFormat(orderRefundModel.getOrderBackup().getPayAmount()));
            tvServiceCharge.setText("-￥" + StringUtils.priceFormat(orderRefundModel.getOrderBackup().getUserFee()));
            tvButTheRefundAmount.setText("￥" + StringUtils.priceFormat(orderRefundModel.getOrderBackup().getCharge()));
        }

        tvRefundType.setText(orderRefundModel.getRefundReason());
        tvRefundDetail.setText(orderRefundModel.getRefundDescription());
        tvRefundDetail.setVisibility(TextUtils.isDigitsOnly(orderRefundModel.getRefundDescription()) ? View.GONE : View.VISIBLE);
        //  图片
        if (!ListUtil.isEmpty(orderRefundModel.getImageUrls())) {
            List<RefundImageEntity> list = new ArrayList<>();
            for (String imageUrl : orderRefundModel.getImageUrls()) {
                list.add(RefundImageEntity.newBuilder().path(imageUrl).type(RefundImageEntity.TYPE_NORMAL).build());
            }
            refundPicListAdapter.addData(list);
        } else {
            includeImages.setVisibility(View.GONE);
        }

        // 退款进度
        if (orderRefundModel.getRefundProgress() != null && !ListUtil.isEmpty(orderRefundModel.getRefundProgress())) {
            List<RefundImageEntity> list = new ArrayList<>();
            View item = null;
            for (OrderRefundModel.RefundProgress refundProgress : orderRefundModel.getRefundProgress()) {
                boolean isReject = false;
                // 退款中
                if (!TextUtils.isEmpty(refundProgress.getStatus()) && refundProgress.getStatus().equals(OrderEntity.statusRefunding)) {
                    item = LayoutInflater.from(this).inflate(R.layout.refund_item_refunding, null);
                }// 已退款
                else if (!TextUtils.isEmpty(refundProgress.getStatus()) && refundProgress.getStatus().equals(OrderEntity.statusRefunded)) {
                    item = LayoutInflater.from(this).inflate(R.layout.refund_item_refunded, null);
                }// 已驳回
                else if (!TextUtils.isEmpty(refundProgress.getStatus()) && refundProgress.getStatus().equals(OrderEntity.statusRejected)) {
                    isReject = true;// 如果是已驳回，则需要在内容前面加'驳回理由：'
                    item = LayoutInflater.from(this).inflate(R.layout.refund_item_reject, null);
                }
                if (item != null) {
                    TextView title = item.findViewById(R.id.tv_title);
                    title.setText(refundProgress.getTitle());
                    TextView content = item.findViewById(R.id.tv_content);
                    if (isReject) {
                        String str1 = "<font color='#7d8090'>驳回理由：</font>" + "<font color='#111111'>" + refundProgress.getContent() + "</font>";
                        content.setText(Html.fromHtml(str1));
                    } else {
                        content.setText(Html.fromHtml(refundProgress.getContent()));
                    }
                    TextView time = item.findViewById(R.id.tv_time);
                    time.setText(TimeUtils.dateToYYYYMMDDHHSS(refundProgress.getTime()));
                    llAfterList.addView(item);
                }
            }
            refundPicListAdapter.addData(list);
        }
        orderEntity = new OrderEntity(orderRefundModel.getOrderBackup());
        tvRefundReason.setText(orderRefundModel.getUserFeeSummary());
        if (!orderEntity.hasServiceCharge()) {
            tvRefundReason.setVisibility(View.INVISIBLE);
        }
        initHeaderView();
    }

    private void startPhotoPage(int index) {
        if (refundPicListAdapter.getData() == null) {
            return;
        }
        List<Photo> photoList = new LinkedList<>();
        for (RefundImageEntity imageEntity : refundPicListAdapter.getData()) {
            photoList.add(Photo.newBuilder()
                    .url(imageEntity.getPath())
                    .build());
        }
        PhotoDetail photoDetail = PhotoDetail.newBuilder()
                .localPhoto(false)
                .photoList(photoList)
                .playIndex(index)
                .build();
        ARouter.getInstance()
                .build(ARouterConfig.PhotoPage)
                .withParcelable("photoDetail", photoDetail)
                .navigation();
    }


    @OnClick(R.id.tv_refund_reason)
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_refund_reason:
                if(orderRefundModel != null){
                    CommonTitleDetailDialog.newInstance(getString(R.string.service_charge_info),orderRefundModel.getUserFeeDetail(),null,getString(R.string.know_the))
                            .show(getSupportFragmentManager(),"");
                }
                break;
        }
    }
}
